/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
Ext.onReady(function() {
    
    var assignments_store = new Ext.data.GroupingStore({
        remoteSort: true,
        groupField: 'paper_id',
        sortInfo: {
            field: 'id',
            direction: 'ASC'
        },
        proxy: new Ext.data.HttpProxy({
            url: 'getassignments'
        }),
        reader: new Ext.data.JsonReader({
            root: 'assignments',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'id'
        },
        {
            name: 'paper_id'
        },
        {
            name: 'reviewer_id'
        },
        {
            name: 'title'
        },
        {
            name: 'reviewer'
        },
        {
            name: 'reviewed',
            type: 'bool'
        },
        {
            name: 'reviews_count'
        },
        {
            name: 'date_assigned',
            type: 'date',
            dateFormat: 'Y-m-d G:i:s'
        },
        {
            name: 'email'
        },
        {
            name: 'isNotified',
			type: 'bool'
        }])
    });
    var filters = new Ext.ux.grid.GridFilters({
        filters: [{
            type: 'string',
            dataIndex: 'title'
        },
        {
            type: 'string',
            dataIndex: 'reviewer'
        }]
    });
    /*    var pagingBar = new Ext.PagingToolbar({
        pageSize: 25,
        store: ds,
        displayInfo: true,
        displayMsg: 'Displaying papers {0} - {1} of {2}',
        emptyMsg: "No papers to display"
    });*/
     function renderReviewed(value, p, r) {
        var yes = '<img src="/../images/2.jpg">';
        var no = '<img src="/../images/1.jpg">';
        if (value > 0) {
            return yes;
        } else {
            return no;
        }
    }
	function renderNotified(value, p, r) {
        var yes = '<img src="/../images/2.jpg">';
        var no = '<img src="/../images/1.jpg">';
        if (value) {
            return yes;
        } else {
            return no;
        }
    }
    function renderEmail(value, p, r) {
        return String.format('<a href="mailto:{0}">{0}</a>', value);
    }
	function renderTitle(value, p, r) {
        return String.format('<b>{0}</b>', r.data['title']);
    }
	var cancelAction = function() {
        var assignments = assignments_grid.getSelectionModel().getSelections();
        var acount = assignments.length;
		var a_list = '';
        if (acount <= 0) {
            Ext.Msg.alert('Information', 'Please select assignments to cancel');
            return;
        }
        for (var i = 0; i < acount; i++) {
            if (i < acount - 1) {
                a_list += assignments[i].id + ':';
            } else {
                a_list += assignments[i].id;
            }
        }
       
        Ext.Ajax.request({
            url: 'cancelassignments',
            success: cancelSuccess,
            failure: cancelFail,
            params: {
                a_list: a_list
            }
        });
    }; 
	
	var notifyAction = function() {
        var assignments = assignments_grid.getSelectionModel().getSelections();
        var acount = assignments.length;
		var a_list = '';
		var r_list = '';
        if (acount <= 0) {
            Ext.Msg.alert('Information', 'Please select assignments to notify');
            return;
        }
        for (var i = 0; i < acount; i++) {
            if (i < acount - 1) {
                a_list += assignments[i].id + ':';
				r_list += assignments[i].data.email + ':';
            } else {
                a_list += assignments[i].id;
				r_list += assignments[i].data.email;
            }
        }
       
        Ext.Ajax.request({
            url: 'notify',
            success: notifySuccess,
            failure: notifyFail,
            params: {
                a_list: a_list,
				r_list: r_list
            }
        });
    }; 
	
    var assignments_grid = new Ext.grid.GridPanel({
        store: assignments_store,
        columns: [{
            header: "Title",
            width: 150,
            dataIndex: 'paper_id',            
			renderer: renderTitle,
            sortable: true
        },
        {
            header: "Reviewer",
            width: 150,
            dataIndex: 'reviewer',
			sortable: true			
        },
        {
            header: "Date assigned",
            width: 130,
            dataIndex: 'date_assigned',
            renderer: Ext.util.Format.dateRenderer('d/m/Y G:i:s'),
            sortable: true
        },
        {
            header: "Reviewed",
            width: 100,
            renderer: renderReviewed,
            dataIndex: 'reviews_count',
			sortable: true
        },
        {
            header: "Email",
            width: 120,            
            renderer: renderEmail,
            dataIndex: 'email'                       
        },
        {
            header: "Notified",
            width: 50,            
            renderer: renderNotified,
            dataIndex: 'isNotified'                       
        }],
        view: new Ext.grid.GroupingView({
            //forceFit: true,
            hideGroupedColumn: true, 
            groupTextTpl: '{text} - Count({[values.rs.length]})'
        }),
		tbar: [{
            text: 'Cancel assignments',
            handler: cancelAction,
            waitMsg: 'Canceling assignments...',
            tooltip: 'Select papers and click to cancel assignments'
        }, ' | ',
		{
            text: 'Notify reviewers',
            handler: notifyAction,
            waitMsg: 'Notifying reviewers...',
            tooltip: 'Select assignments and click to notify reviewers'
        }],
		
        plugins: filters,
        renderTo: 'assignments-grid',
        width: 650,
        height: 600,
        title: 'Assignments',
        frame: true,
        loadMask: true
    });    
    
	
	var cancelSuccess = function() {
        Ext.Msg.alert('Information', 'Assignments canceled successfully');
        assignments_store.load();
    };
    var cancelFail = function() {};
	var notifySuccess = function() {
        Ext.Msg.alert('Information', 'Reviewers notified successfully');
        assignments_store.load();
    };
    var notifyFail = function() {};
	var reviewers_store = new Ext.data.Store({
        remoteSort: true,
        sortInfo: {
            field: 'last_name',
            direction: 'ASC'
        },
        proxy: new Ext.data.HttpProxy({
            url: 'reviewers'
        }),
        reader: new Ext.data.JsonReader({
            root: 'reviewers',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'first_name'
        },
        {
            name: 'last_name'
        },
        {
            name: 'institution'
        },
        {
            name: 'email'
        },
        {
            name: 'total_papers'
        }])
    });
	var rpagingBar = new Ext.PagingToolbar({
        pageSize: 100,
        store: reviewers_store,
        displayInfo: true,
        displayMsg: 'Displaying reviewers {0} - {1} of {2}',
        emptyMsg: "No reviewers to display"
    });
	var assignAction = function() {
        var reviewers = reviewers_grid.getSelectionModel().getSelections();
        var papers = assignments_grid.getSelectionModel().getSelections();

        var r_list = '';
        var rcount = reviewers.length;
        if (rcount <= 0) {
            Ext.Msg.alert('Information', 'Please select reviewers');
            return;
        }
        for (var i = 0; i < rcount; i++) {
            if (i < rcount - 1) {
                r_list += reviewers[i].id + ':';
            } else {
                r_list += reviewers[i].id;
            }
        }
        var p_list = '';
        var pcount = papers.length;
        if (pcount <= 0) {
            Ext.Msg.alert('Information', 'Please select papers to assign');
            return;
        }
        for (var i = 0; i < pcount; i++) {
            if (i < pcount - 1) {
                p_list += papers[i].data.paper_id + ':';
            } else {
                p_list += papers[i].data.paper_id;
            }
        }
        Ext.Ajax.request({
            url: 'assign',
            success: assignSuccess,
            failure: assignFail,
            params: {
                rList: r_list,
                pList: p_list
            }
        });
    };
	

	var reviewers_grid = new Ext.grid.GridPanel({
        store: reviewers_store,
        columns: [{
            header: "Last Name",
            width: 100,
            dataIndex: 'last_name',
            sortable: true
        },
        {
            header: "First Name",
            width: 100,
            dataIndex: 'first_name',
            sortable: true
        },
        {
            header: "Institution",
            width: 100,
            dataIndex: 'institution',
            sortable: true
        },
        {
            header: "Total assigned",
            width: 50,
            dataIndex: 'total_papers',
            sortable: true
        }],
        renderTo: 'reviewers-grid',
        width: 350,
        height: 600,
        title: 'Reviewers',
        frame: true,
        loadMask: true,
        bbar: rpagingBar,
        waitMsgTarget: true,
        viewConfig: {
            forceFit: true
        },
        tbar: [{
            text: 'Assign',
            handler: assignAction,
            waitMsg: 'Assigning papers...',
            tooltip: 'Select papers and click to assign to selected reviewers'
        }]
    });
	
	var assignSuccess = function() {
        Ext.Msg.alert('Information', 'Papers assigned successfully');
        assignments_store.load();
        reviewers_store.load({
            params: {
                start: 0,
                limit: 25
            }
        });
    };
    var assignFail = function() {}; 
	
    assignments_store.load();
	reviewers_store.load({
        params: {
            start: 0,
            limit: 100
        }
    });
});